/*
 * @Description:公交或站点详细查询页面
 * @Author: jun.fu
 * @Date: 2019-03-07 17:38:02
 * @Last Modified by:   jun.fu
 * @Last Modified time: 2019-03-07 17:38:02
 */
import React, { Component } from 'react'
import { StyleSheet, Text, View, ScrollView, TouchableOpacity, Image } from 'react-native'
import SearchItem from '../components/SearchCar/components/SearchItem'
import InputTitleBar from '../components/public/InputTitleBar'
import RefreshListView, { RefreshState } from '../utils/RefreshListView'
import { px2dp } from 'rn-xiaobu-utils'
import { getImportDataFull } from '../components/SearchCar/api/api'
import MyPosition from '../components/SearchCar/components/MyPosition'
import XiaobuStorage from '../utils/XiaobuStorage';

export default class SearchDetails extends Component {
  state = {
    list: [],
    searchText: '',
    refreshState: RefreshState.Idle,
    historyList: []
  }

  constructor(props) {
    super(props)
    this.pageNum = 1
    this.pageSize = 15
  }

  static navigationOptions = ({ navigation }) => {
    // 自定义输入框标题栏
    return {
      headerTitle: (
        <InputTitleBar
          back={navigation.getParam('back')}
          changeText={navigation.getParam('changeText')}
          defaultText={navigation.getParam('searchText')}
        />
      ),
      headerLeft: null
    }
  }

  /**
   * 返回上一页
   */
  back = () => {
    this.props.navigation.goBack()
  }

  /**
   * 输入框文字更改监听函数
   * @param {String} text 更改后的文字
   */
  changeText = text => {
    this.pageNum = 1
    if (text) {
      this.setState(
        {
          searchText: text,
          list: []
        },
        () => {
          if (this.state.searchText) {
            this.onHeaderRefresh()
          }
        }
      )
    } else {
      this.setState({
        searchText: '',
        list: []
      }, ()=>{
        this.initHistory()
      })
    }
  }

  initHistory = () => {
    if (!this.props.navigation.getParam('notShowCache')) {
      XiaobuStorage.getItem(this.props.navigation.getParam('cacheKey') || '').then(res=>{
        if (res) {
          this.setState({
            historyList: JSON.parse(res)
          })
        }
      })
    }
  }

  /**
   * 获取列表数据
   * @returns {Promise<any> | Promise<*>}
   */
  getListData = () => {
    return new Promise((resolve, reject) => {
      this.setState(
        {
          upState: this.state.searchText
        },
        () => {
          // ajaxAsync('/bus/import', {
          //   IMPORT: this.state.searchText,
          //   PAGE_CAPACITY: this.pageSize,
          //   PAGE_INDEX: this.pageNum
          // }).then(res => {
          //   if (this.props.navigation.getParam('type') === 1 || this.props.navigation.getParam('type') === 2) {
          //     this.pageNum = this.pageNum + 1
          //     this.setState({
          //       list: this.pageNum === 1 ? [].concat(res.BUS_LIST || []) : this.state.list.concat(res.BUS_LIST || [])
          //
          //     }, () => {
          //       resolve({ currentLength: (res.BUS_LIST && res.BUS_LIST.length) || 0, length: this.state.list.length })
          //     })
          //   } else {
          //     this.pageNum = this.pageNum + 1
          //     this.setState({
          //       list: this.pageNum === 1 ? [].concat(res.STATION_LIST || []) : this.state.list.concat(res.STATION_LIST || [])
          //
          //     }, () => {
          //       resolve({ currentLength: (res.STATION_LIST && res.STATION_LIST.length) || 0, length: this.state.list.length })
          //     })
          //   }
          // }).catch(err => {
          //   this.setState({
          //     refreshState: RefreshState.Failure
          //   })
          //   reject(err)
          // })
          getImportDataFull(
            this.state.searchText,
            this.pageNum,
            this.pageSize,
            this.props.navigation.getParam('type')
          )
            .then(res => {
              this.setState(
                {
                  list:
                    this.pageNum === 1
                      ? [].concat(res.list)
                      : this.state.list.concat(res.list)
                },
                () => {
                  resolve({ currentLength: res.list.length, length: res.count })
                }
              )
              this.pageNum = this.pageNum + 1
            })
            .catch(error => {
              this.setState({
                refreshState: RefreshState.Failure
              })
              reject(error)
            })
        }
      )
    })
  }

  /**
   * 清除历史记录
   */
  cleanHistory = ()=>{
    this.setState({
      historyList: []
    })
    XiaobuStorage.removeItem(this.props.navigation.getParam('cacheKey'))
  }

  /**
   * 渲染查询结果列表
   * @param {{id,name,type,lat,lng}} item
   * @returns {*}
   * @private
   */
  _renderItem = ({ item, index }) => {
    if (this.props.navigation.getParam('shouldBack')) {
      // 点击后需要返回，用于线路规划等
      return (
        <SearchItem
          key={index}
          name={item.name}
          id={item.id}
          shouldBack={this.props.navigation.getParam('shouldBack')}
          itemOnPress={this.props.navigation.getParam('getInfo')}
          type={item.type}
          lat={item.lat}
          lng={item.lng}
          cacheKey={this.props.navigation.getParam('cacheKey') || ''}
        />
      )
    } else {
      // 默认的点击后前进
      return (
        <SearchItem
          key={index}
          name={item.name}
          id={item.id}
          type={item.type}
          lat={item.lat}
          lng={item.lng}
          cacheKey={this.props.navigation.getParam('cacheKey') || ''}
        />
      )
    }
  }

  /**
   * 下拉刷新
   */
  onHeaderRefresh = () => {
    this.pageNum = 1
    this.setState(
      {
        refreshState: RefreshState.HeaderRefreshing,
        list: []
      },
      () => {
        this.getListData().then(res => {
          this.setState({
            // 当前页长度小于需要的长度或者（当前页长度+前几页*需要的长度>总长度）,则认为没有下一页
            refreshState:
              res.currentLength < this.pageSize ||
              res.length < (this.pageNum - 2) * this.pageSize + this.pageSize
                ? RefreshState.NoMoreData
                : RefreshState.Idle
          })
        })
      }
    )
  }

  /**
   * 上拉加载
   */
  onFooterRefresh = () => {
    this.setState({ refreshState: RefreshState.FooterRefreshing }, () => {
      this.getListData().then(res => {
        this.setState({
          // 当前页长度小于需要的长度或者（当前页长度+前几页*需要的长度>总长度）,则认为没有下一页
          refreshState:
            res.currentLength < this.pageSize ||
            res.length < (this.pageNum - 2) * this.pageSize + this.pageSize
              ? RefreshState.NoMoreData
              : RefreshState.Idle
        })
      })
    })
  }

  /**
   * 列表头部渲染
   * @returns {*}
   * @private
   */
  _ListHeaderComponent = () => {
    return (
      <Text style={styles.title}>
        {this.props.navigation.getParam('type') === 3 ? '车站' : '线路'}
      </Text>
    )
  }

  componentDidMount() {
    // 设置返回函数以及文字改变函数
    this.props.navigation.setParams({
      back: this.back,
      changeText: this.changeText
    })
    // 进入页面时，根据前面一页的参数查询一次
    this.changeText(this.props.navigation.getParam('searchText'))
  }

  render() {
    return (
      <View style={styles.container}>
        {/* 是否渲染我的位置 */}
        {this.props.navigation.getParam('needMyPosition') ? (
          <MyPosition itemOnPress={this.props.navigation.getParam('getInfo')} />
        ) : null}
        {this.state.list.length > 0 ? (
          <RefreshListView
            style={{ flex: 1, zIndex: 2 }}
            data={this.state.list}
            extraData={this.state}
            keyExtractor={(item, index) => index + ''}
            refreshState={this.state.refreshState}
            onHeaderRefresh={this.onHeaderRefresh}
            onFooterRefresh={this.onFooterRefresh}
            renderItem={this._renderItem}
            ListHeaderComponent={this._ListHeaderComponent}
            footerRefreshingText="玩命加载中 >.<"
            footerFailureText="我擦嘞，居然失败了 =.=!"
            footerNoMoreDataText="-我是有底线的-"
            footerEmptyDataText="-好像什么东西都没有-"
          />
        ) : !this.state.searchText && this.state.historyList.length > 0 ? <ScrollView style={{ flex: 1, zIndex: 2 }}>
          <Text style={styles.title}>搜索历史</Text>
          {this.state.historyList.map((item, index)=>(
            this._renderItem({ item, index })
          ))}
          <TouchableOpacity onPress={this.cleanHistory}>
            <Text style={styles.cleanHistory}>清空历史搜索</Text>
          </TouchableOpacity>
        </ScrollView> : null}
        <Image
          style={{
            width: '100%',
            height: px2dp(360),
            position: 'absolute',
            bottom: 0,
            zIndex: 1
          }}
          source={require('../../assets/img/background.png')}
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F2F5F6'
  },

  title: {
    height: px2dp(74),
    backgroundColor: '#F2F5F6',
    color: '#999999',
    paddingLeft: px2dp(30),
    lineHeight: px2dp(74)
  },
  cleanHistory: {
    height: px2dp(100),
    lineHeight: px2dp(100),
    backgroundColor: '#ffffff',
    flexDirection: 'row',
    alignItems: 'center',
    textAlign: 'center'
  }
})
